/*
 * Copyright (c) 2021 chwxu@outlook.com
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of
 *    conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list
 *    of conditions and the following disclaimer in the documentation and/or other materials
 *    provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors may be used
 *    to endorse or promote products derived from this software without specific prior written
 *    permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
import mysql from "mysql2";
// import { openHarmonySigCommits } from "./openharmony-sig-commits";

function renewConnection() {
    return mysql.createConnection({
        host: 'www.dongmantang.com',
        user: 'root',
        password: process.env.REMOTE_DATABASE_PASSWD,
        database: 'oh_commits',
    });
}

var connection = renewConnection();

function checkConnection() {
    try {
        connection.query('SELECT 1');
    } catch (e) {
        connection = renewConnection();
    }
}

// var query_result = null;
// var query_fields = null;


export const getCommitList = (() => {
    const result: any[] = [];

    // openHarmonySigCommits.forEach((commitDict) => {
    //     result.push(commitDict);
    // })

    checkConnection();
    connection.query(
        'SELECT * FROM `COMMITS_OF_MERGED_PR` ORDER BY `CLOSED_AT` DESC',
        // 'SELECT * FROM `COMMITS_OF_MERGED_PR` WHERE `PROJECT`="openharmony" ORDER BY `CLOSED_AT` DESC',
        function (err, res, fields) {
            // console.error(err);
            // console.log(res);
            const query_result = JSON.parse(JSON.stringify(res));
            // console.log(fields);
            // const query_fields = fields;
            query_result.forEach((commitDict: any) => {
                result.push({
                    key: commitDict.SHA,
                    project: commitDict.PROJECT,
                    repo: commitDict.REPOSITORY,
                    pr_number: commitDict.PR_NUMBER,
                    closed_at: commitDict.CLOSED_AT,
                    sha: commitDict.SHA,
                    author_id: commitDict.AUTHOR_ID,
                    author_name: commitDict.AUTHOR_NAME,
                    author_email: commitDict.AUTHOR_EMAIL,
                    addition: commitDict.ADDITIONS,
                    deletion: commitDict.DELETIONS,
                });
            });
        },
    );

    // console.log(result);
    return result;
})();


export const getMonthlyStat = (() => {
    const result: any[] = []

    const monthInterval = [
        ['2021-01-01 00:00:00', '2021-02-01 00:00:00'],
        ['2021-02-01 00:00:00', '2021-03-01 00:00:00'],
        ['2021-03-01 00:00:00', '2021-04-01 00:00:00'],
        ['2021-04-01 00:00:00', '2021-05-01 00:00:00'],
        ['2021-05-01 00:00:00', '2021-06-01 00:00:00'],
        ['2021-06-01 00:00:00', '2021-07-01 00:00:00'],
        ['2021-07-01 00:00:00', '2021-08-01 00:00:00'],
        ['2021-08-01 00:00:00', '2021-09-01 00:00:00'],
        ['2021-09-01 00:00:00', '2021-10-01 00:00:00'],
        ['2021-10-01 00:00:00', '2021-11-01 00:00:00'],
        ['2021-11-01 00:00:00', '2021-12-01 00:00:00'],
        ['2021-12-01 00:00:00', '2022-01-01 00:00:00'],
    ];

    checkConnection();
    monthInterval.forEach((dataPair) => {
        connection.query(
            "SELECT COUNT(*) FROM `oh_commits`.`COMMITS_OF_MERGED_PR` WHERE `CLOSED_AT` >= ? AND `CLOSED_AT` < ?",
            dataPair,
            (err, res, fields) => {
                // console.error(err);
                // console.log(res);
                result.push(JSON.parse(JSON.stringify(res))[0]['COUNT(*)']);
                // console.log(result);
                // console.log(result[0]['COUNT(*)']);
            },
        );
    })

    return { 'items': result, 'total': 12 };
})();
